package com.ityj.yygh.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ityj.yygh.hospital.repository.HospitalRepository;
import com.ityj.yygh.hospital.service.HospitalService;
import com.ityj.yygh.cmn.client.DictFeignClient;
import com.ityj.yygh.constant.HosptialConstant;
import com.ityj.yygh.model.hosp.Hospital;
import com.ityj.yygh.vo.hosp.HospitalQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public boolean save(Map<String, Object> stringObjectMap) {
        // data verify and transfer to Hospital
        if (stringObjectMap == null) {
            log.warn("input parameter stringObjectMap is null!");
            return false;
        }
        String jsonString = JSONObject.toJSONString(stringObjectMap);
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        // verify existence
        Hospital existHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        if (existHospital == null) {
            // not exist
            hospital.setStatus(0);
            hospital.setIsDeleted(0);
            hospital.setCreateTime(new Date());
        } else {
            log.info("{} is exist and will update it!", hospital.getHoscode());
            hospital.setStatus(existHospital.getStatus());
            hospital.setIsDeleted(existHospital.getIsDeleted());
            hospital.setCreateTime(existHospital.getCreateTime());
        }
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
        return true;
    }

    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        return hoscode.isEmpty() ? new Hospital() : hospitalRepository.getHospitalByHoscode(hoscode);
    }

    @Override
    public Page<Hospital> searchHopitalInfoByCondition(HospitalQueryVo hospitalQueryVo, Integer pageNum, Integer pageSize) {
        // 创建Pageable对象，设置当前页及每页的大小
        // page – zero-based page index.
        Pageable pageable = PageRequest.of(pageNum - 1 , pageSize);
        //创建Example对象，用于放查询的条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        // 根据前端传过来的hospitalQueryVo，构造一个Hospital对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        hospital.setIsDeleted(0);
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        hospitalPage.getContent().forEach(this::fillHospParamInfo);
        return hospitalPage;
    }

    public void fillHospParamInfo(Hospital hospital) {
        String hostypeName = dictFeignClient.getDictName(hospital.getHostype(), HosptialConstant.HOS_TYPE);

        String provinceName = dictFeignClient.getDictName(hospital.getProvinceCode());
        String cityName = dictFeignClient.getDictName(hospital.getCityCode());
        String districtName = dictFeignClient.getDictName(hospital.getDistrictCode());

        hospital.getParam().put("address", provinceName + cityName + districtName);
        hospital.getParam().put("hostypeName", hostypeName);
    }

    // 更新医院的状态
    @Override
    public void updateHospitalStatus(String id, Integer status) {
        Optional<Hospital> hospitalOptional = hospitalRepository.findById(id);
        if (hospitalOptional.isPresent()) {
            Hospital hospital = hospitalOptional.get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        } else {
            log.warn("Can't find the data of id: {}", id);
        }

    }

    @Override
    public Map<String, Object> findHospDetailById(String id) {
        Map<String, Object> result = new HashMap<>();
        Optional<Hospital> hospitalOptional = hospitalRepository.findById(id);
        if (!hospitalOptional.isPresent()) {
            log.warn("The data of id:{} doesn't exist!", id);
            return result;
        }
        Hospital hospital = hospitalOptional.get();
        this.fillHospParamInfo(hospital);
        result.put("hospital", hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public String getHospName(String hoscode) {
        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospitalByHoscode.getHosname();
    }

    @Override
    public List<Hospital> findByHositalNameLike(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> findItemDetail(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.getHospitalByHoscode(hoscode);
        fillHospParamInfo(hospital);
        result.put("hospital", hospital);
        result.put("bookingRule", hospital.getBookingRule());

        return result;
    }
}
